package com.ruoyi.web.controller.translation;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/10/10
 */
public class BaiduTranslator {


    // 百度翻译API配置
    private static final String APP_ID = "20230328001617974";
    private static final String SECRET_KEY = "t7Dc2keNnkPYSEcTSQL6";
    private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private final CloseableHttpClient httpClient;
    private final ObjectMapper objectMapper;

    // 百度翻译支持的语言代码
    public static final Map<String, String> LANGUAGE_CODES = new HashMap<String, String>() {
        {
            //柬埔寨语	菲律宾语 马来语	泰米尔语 泰国语 葡萄牙语	越南语 缅甸语	印地语 印度尼西亚语

            put("中文", "zh");
            put("英语", "en");
            put("日语", "jp");
            put("韩语", "kor");
            put("法语", "fra");
            put("西班牙语", "spa");
            put("泰语", "th");
            put("阿拉伯语", "ara");
            put("俄语", "ru");

            put("德语", "de");
            put("意大利语", "it");
            put("希腊语", "el");
            put("荷兰语", "nl");
            put("波兰语", "pl");
            put("保加利亚语", "bul");
            put("爱沙尼亚语", "est");
            put("丹麦语", "dan");
            put("芬兰语", "fin");
            put("捷克语", "cs");
            put("罗马尼亚语", "rom");
            put("斯洛文尼亚语", "slo");
            put("瑞典语", "swe");
            put("匈牙利语", "hu");
            put("繁体中文", "cht");


            put("柬埔寨语", "kh");
            put("菲律宾语", "fil");
            put("马来语", "ms");
            put("泰米尔语", "tam");
            put("泰国语", "th");
            put("葡萄牙语", "pt");
            put("越南语", "vie");
            put("缅甸语", "bur");
            put("印地语", "hi");
            put("印度尼西亚语", "id");

        }
    };

    public BaiduTranslator() {
        this.httpClient = HttpClients.createDefault();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * MD5加密
     */
    private String md5(String string) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(string.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }

    /**
     * 生成签名
     */
    private String generateSign(String query, String salt) {
        String signStr = APP_ID + query + salt + SECRET_KEY;
        return md5(signStr);
    }

    /**
     * 单条文本翻译
     */
    public String translate(String query, String targetLang) {
        return translate(query, "zh", targetLang);
    }
    public String translateTwo(String query, String sour, String targetLang) {
        return translate(query, sour, targetLang);
    }
    /**
     * 翻译方法
     */
    public String translate(String query, String sourceLang, String targetLang) {
        try {
            // 生成随机盐值
            String salt = String.valueOf(System.currentTimeMillis());

            // 生成签名
            String sign = generateSign(query, salt);

            // 构建请求参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("q", query));
            params.add(new BasicNameValuePair("from", sourceLang));
            params.add(new BasicNameValuePair("to", targetLang));
            params.add(new BasicNameValuePair("appid", APP_ID));
            params.add(new BasicNameValuePair("salt", salt));
            params.add(new BasicNameValuePair("sign", sign));

            // 创建HTTP请求
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");

                // 解析响应
                JsonNode jsonNode = objectMapper.readTree(result);

                // 检查错误码
                if (jsonNode.has("error_code")) {
                    String errorCode = jsonNode.get("error_code").asText();
                    String errorMsg = jsonNode.get("error_msg").asText();
                    throw new RuntimeException("百度翻译API错误: " + errorCode + " - " + errorMsg);
                }

                // 提取翻译结果
                JsonNode transResult = jsonNode.get("trans_result");
                if (transResult != null && transResult.isArray()) {
                    StringBuilder translatedText = new StringBuilder();
                    for (JsonNode item : transResult) {
                        if (item.has("dst")) {
                            if (translatedText.length() > 0) {
                                translatedText.append("\n");
                            }
                            translatedText.append(item.get("dst").asText());
                        }
                    }
                    return translatedText.toString();
                }

                throw new RuntimeException("未找到翻译结果");
            }

        } catch (Exception e) {

            //throw new RuntimeException("翻译失败: " + e.getMessage() + targetLang, e);
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 批量翻译
     */
    public List<String> translateBatch(List<String> queries, String targetLang) {
        List<String> results = new ArrayList<>();
        for (String query : queries) {
            try {
                // 添加延迟避免频率限制
                Thread.sleep(200);
                String result = translate(query, targetLang);
                results.add(result);
            } catch (Exception e) {
                results.add("翻译失败: " + query);
                System.err.println("翻译失败: " + e.getMessage());
            }
        }
        return results;
    }

    /**
     * 获取支持的语言列表
     */
    public Map<String, String> getSupportedLanguages() {
        return new HashMap<>(LANGUAGE_CODES);
    }

    public void close() {
        try {
            httpClient.close();
        } catch (Exception e) {
            System.err.println("关闭HTTP客户端失败: " + e.getMessage());
        }
    }
}
